package com.lewis.demo.roketmq.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Lewis
 * @Date: 2020/4/21 11:17
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/mqProducer")
public class MQProducerController {

    @Resource
    DefaultMQProducer defaultMQProducer;

    /**
     * 发送简单的MQ消息
     * @param msg
     * @return
     */
    @GetMapping("/send")
    public JSONObject send(String msg) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        JSONObject resultJson = new JSONObject();
        if (StringUtils.isEmpty(msg)) {
            resultJson.put("code", 0);
            resultJson.put("msg", "消息为空");
            return resultJson;
        }

        log.info("发送MQ消息内容：" + msg);
        Message sendMsg = new Message("TestTopic", "TestTag", msg.getBytes());

        // 默认3秒超时
        SendResult sendResult = defaultMQProducer.send(sendMsg);
        log.info("消息发送响应：" + sendResult.toString());

        resultJson.put("code", 200);
        resultJson.put("msg", sendResult);

        return resultJson;
    }

}